<?php

class Admin_manage_service extends MY_Service {

    function __construct() {
        parent::__construct();
        $this->load->model("common_model", "common");
        $this->load->model("admin_user_model", "user");
        $this->load->model("admin_role_model", "role");
        $this->load->model("admin_operation_log_model", "operation_log");

        $this->load->library('session');
        $this->load->library("layout", array("type" => "admin"));
        define("MANAGE_URL", ADMIN_URL);

        $this->addLog();
    }

    /*
     * 是否登录
     */

    function loginAdminInfo() {

        $outArr = array();

        $user_id = $this->session->session_admin_user_id;
        if (!empty($user_id)) {
            $result = $this->user->getDataById($user_id);
            if (!empty($result)) {//如果用户表存在
                $role = $this->role->getDataById($result["role_id"]);
                if (!empty($role)) {
                    $result["menu"] = $role["menu"];
                    $result["power"] = $role["power"];
                    $result["role"] = $role;
                } else {
                    $result["menu"] = "";
                    $result["power"] = "";
                    $result["role"] = [];
                }

                $outArr = $result;
            }
        }
        return $outArr;
    }

    /*
     * 检查是否登录
     */

    function checkAdminLogin() {

        $adminInfo = $this->loginAdminInfo();
        if ($adminInfo) {
            $outArr = $adminInfo;
        } else {
            //echo time();
            //redirect(ADMIN_URL."&c=login");
            echo "<script>window.top.location.href='" . MANAGE_URL . "&c=login'</script>";
            exit;
        }
        return $outArr;
    }

    /*
     * 检查权限
     */

    function checkPower($paramArr = array()) {

        $flag = 0;

        $adminInfo = $this->loginAdminInfo();

        $optionArr = array(
            "power" => "",
            "ajax" => 0,
        );
        if (!empty($paramArr)) {
            $optionArr = array_merge($optionArr, $paramArr);
        }
        extract($optionArr);
        if ($power != "") {
            if (strrpos($adminInfo["power"], "|" . $power . "|") !== false || $adminInfo["role_id"] == -1) {
                $flag = 1;
            }
        }
        if ($flag == 0) {
            throw new Exception("您没有此操作权限");
        }
    }

    public function addLog() {

        $is_ajax = $this->input->is_ajax_request();
        if ($is_ajax) {
            $params = $this->input->post();
            $d = $this->router->fetch_directory();
            $c = $this->router->fetch_class(); //获取控制器名
            $m = $this->router->fetch_method(); //获取方法名
            if (!empty($params)) {
                $action_name = $d . $c . "/" . $m;
                $this->operation_log->addOperationLog(0, 0, $action_name, [
                    "params" => $params,
                ]);
            }
        }
    }

}
